<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/6/15
 * Time: 9:43
 */

namespace app\tms\controller;

use app\mini\model\Store;
use app\mini\model\StoreOrderDetail;
use app\tms\job\TaskSms;
use app\tms\model\DeliverCar;
use app\tms\model\DeliverDriverAccountLog;
use app\tms\model\DeliverTask;
use app\tms\model\DeliverTaskImg;
use app\tms\model\StoreOrder;
use app\tms\model\StoreOrderProfit;
use Exception;
use think\db\exception\DbException;
use think\facade\Queue;
use think\facade\Request;
use think\Response;

class Task extends Base
{

    /**
     * 更换车牌
     * @param $carNo
     * @return Response
     */
    public function changeCarNo($carNo): Response
    {
        redis()->set('tms:driver:car' . $this->user_id, $carNo);
        return $this->success('请求成功');
    }

    /**
     * 车牌列表
     * @param int $limit
     * @return Response
     */
    public function carNoList(int $limit = 10): Response
    {
        $list = DeliverCar::gs($this->company_id)->field('id,no')->paginate($limit);
        return $this->success('请求成功', compact('list'));
    }

    /**
     * 任务列条
     * @param int $task_status
     * @param int $limit
     * @return Response
     * @throws DbException
     */
    public function list(int $task_status = 1, int $limit = 10): Response
    {
        //新任务(未领取)数量
        $newTaskCount = DeliverTask::user($this->user_id)->taskStatus(1)->count();
        //进行中的任务数量
        $doingTaskCount = DeliverTask::user($this->user_id)->taskStatus(2)->count();
        //已完成任务数量
        $doneTaskCount = DeliverTask::user($this->user_id)->taskStatus(3)->count();
        //任务列表
        $list = DeliverTask::user($this->user_id)->taskStatus($task_status)->order('id desc')->paginate($limit)->each(function ($item) {
            //获取订单ID
            $order_ids = $item->storeOrders()->column('id');
            //门店数
            $store_ids = StoreOrder::whereIn('id', $order_ids)->group('store_id')->column('store_id');
            //商品数
            $item->goods_count = StoreOrderDetail::whereIn('store_order_id', $order_ids)->sum('quantity');
//            $item->store_count = Store::where('deliver_line_id', $item->deliver_line_id)->count();//网点数
            $item->store_count = count($store_ids);
            $item->start_time  = setDates($item->start_time);
            $item->end_time    = setDates($item->end_time);
        });
        return $this->success('请求成功', compact('list', 'newTaskCount', 'doingTaskCount', 'doneTaskCount'));
    }


    /**
     * 任务明细
     * @param int $id
     * @param int $limit
     * @return Response
     * @throws DbException
     */
    public function detail(int $id, int $limit = 10): Response
    {
        $detail = DeliverTask::user($this->user_id)->find($id);
        if (!$detail) return $this->error('任务不存在');
        $order_ids           = $detail->storeOrders()->column('id');//获取订单ID
        $detail->goods_count = StoreOrderDetail::whereIn('store_order_id', $order_ids)->sum('quantity');//商品数
//        $detail->store_count = Store::where('deliver_line_id', $detail->deliver_line_id)->count();//网点数
        // 2024.09.20增加任务门店返回字段long（经度）、lat（纬度）
        // 2024.09.20增加过滤，当天未下单商品的门店不再显示，wherein了一个订单内门店ID集，可能会导致索引失效，如果影响查询速度需要优化
        $store_ids = StoreOrder::whereIn('id', $order_ids)->group('store_id')->column('store_id');
        $detail->store_count = count($store_ids);
        $detail->stores      = Store::where('deliver_line_id', $detail->deliver_line_id)->whereIn('id',$store_ids)->field('id,name,address,long,lat')->select()->each(function ($item) use ($detail,$id) {
            $order_ids         = $detail->storeOrders()->where('store_id', $item->id)->column('id'); //获取订单ID
            $item->goods_count = StoreOrderDetail::whereIn('store_order_id', $order_ids)->sum('quantity');//商品数量

            $field              = "goods_id,goods_rule_id,sum(quantity) quantity";
            $item->goods_detail = StoreOrderDetail::whereIn('store_order_id', $order_ids)->field($field)->group('goods_rule_id')->select()->each(function ($value) {
                $value->goods_name = $value->goods()->value('name');
                $value->spec_name  = $value->goodsRule()->value('spec_name');
            });//商品明细
            // 拍照凭证
            $item->imgs = DeliverTaskImg::where('deliver_task_id', $id)->where('store_id', $item->id)->field('id,img')->select();
        });
        $detail->start_time  = setDates($detail->start_time);
        $detail->end_time    = setDates($detail->end_time);
        return $this->success('获取成功', compact('detail'));
    }


    //任务开始
    public function start($ids): Response
    {
        //获取当前使用车辆
        try {
            $carInfo = $this->getCarInfo($this->user_id);
            if (!DeliverTask::gs($this->company_id)->whereIn('id', $ids)->update(['task_status' => 2, 'start_time' => time(),'deliver_car_id'=> $carInfo['id']])) {
                exception('领取失败');
            }
        }catch (Exception $e){
            return $this->error($e->getMessage());
        }
        Queue::later(config('queue.task_sms.overtime'), TaskSms::class, ["task_ids" => $ids,'mobile'=> $this->userInfo->mobile], "task_sms");
        return $this->success('领取成功');
    }

    //任务结束
    public function end($id): Response
    {
        $model = new DeliverTask();
        $model->startTrans();
        try {
            $info = DeliverTask::gs($this->company_id)->where('id', $id)->find();
            $order_ids           = $info->storeOrders()->column('id');//获取订单ID
            $store_ids = StoreOrder::whereIn('id', $order_ids)->group('store_id')->column('store_id');
            // 获取提交过的凭证
            $img_store_ids = DeliverTaskImg::where('deliver_task_id', $id)->group('store_id')->column('store_id');
            // 如果存在没有提交图片凭证的门店，不允许结束任务
            $missing_store_ids = array_diff($store_ids, $img_store_ids);;
            if (!empty($missing_store_ids)) {
                exception('请上传图片！');
            }
            if (!DeliverTask::gs($this->company_id)->where('id', $id)->update(['task_status' => 3, 'end_time' => time()])) {
                exception('结束失败');
            }
            //结束任务需要添加账户的钱
            $ids    = StoreOrder::where('deliver_task_id', $id)->column('id');
            $profit = StoreOrderProfit::whereIn('store_order_id', $ids)->sum('driver_profit');
            DeliverDriverAccountLog::create([
                'company_id'        => $this->company_id,
                'deliver_driver_id' => $this->user_id,
                'amount'            => $profit,
                'money'             => $this->userInfo->money,
            ]);
            // $this->userInfo->inc('money', $profit)->update();//修改余额
            $this->userInfo->inc('money', $profit)->save();//修改余额
            $model->commit();
            return $this->success('结束成功');
        } catch (Exception $e) {
            $model->rollback();
            return $this->error($e->getMessage());
        }
    }

    //任务图片
    public function submitImg(): Response
    {
        $param = request()->param();
        $model = new DeliverTaskImg();
        $model->startTrans();
        try {
            $param['deliver_driver_id'] = $this->user_id;
            $model->create($param);
        }catch (Exception $e){
            $model->rollback();
            return $this->error('创建失败' . $e->getMessage());
        }
        $model->commit();
        return $this->success('创建成功');
    }

    // 删除图片
    public function delImg(): Response
    {
        $param = request()->param();
        $model = new DeliverTaskImg();
        $model->startTrans();
        try {
            $model->destroy(explode(',', $param['id']));
            $model->commit();
        } catch (Exception $e) {
            $model->rollback();
            return $this->error($e->getMessage());
        }
        return $this->success('删除成功');
    }

    /**
     * 修改门店位置信息
     */
    public function editPosition(): Response
    {
        $param = request()->param();
        
        if(!isset($param['store_id']) || $param['store_id'] == ''){
            return $this->error('请提交门店id');
        }
        $store_id = $param['store_id'];
        $storeInfo = Store::find($store_id);
        if(!$storeInfo){
            return $this->error('请提交正确的门店id');
        }
        try {
            $data = [];
            if(isset($param['address']) && $param['address'] != ''){
                $data['address'] = $param['address'];
            }
            if(isset($param['long']) && $param['long'] != ''){
                $data['long'] = $param['long'];
            }
            if(isset($param['lat']) && $param['lat'] != ''){
                $data['lat'] = $param['lat'];
            }
            $storeInfo->where('id', $store_id)->update($data);
        }catch (Exception $e){
            return $this->error($e->getMessage());
        }
        return $this->success('请求成功');
    }

}